package com.ntd.study.base.thread.process.control;

import cn.hutool.core.lang.Console;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;

/**
 * CountDownLatch： 闭锁，只有其他所有线程的运算全部完成，当前运算才继续执行
 */
public class DemoCountDownLatch {
    static Object object = new Object();
    // 调用够 10 次countDown 就放开运行
    static CountDownLatch latch = new CountDownLatch(10);
    // 调用 10 次await 就放开运行
    static CyclicBarrier cyclicBarrier = new CyclicBarrier(10);
    // 信号量 - 同时允许几个线程经过自己进行执行
    static Semaphore semaphore = new Semaphore(8);
    static Runnable runnable = () -> {
        try {
            synchronized (object) {
                Console.log("进入方法。。。。。");
            }
            cyclicBarrier.await();
            Console.log("栅栏测试输出-----");
            semaphore.acquire();
            Console.log("信号量测试输出-----");
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
            Console.log("闭锁测试输出-----");
            semaphore.release(); // 放开一个信号位
        }
    };

    public static void main(String[] args) throws InterruptedException {
        final long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            new Thread(runnable).start();
        }
        latch.await(); // 当数值为0时继续执行，否则等待
        final long end = System.currentTimeMillis();
        Console.log("耗费时间：" + (end - start));
    }


}
